package cn.edu.cimv.controller;

import cn.edu.cimv.constant.InfoConstant;
import cn.edu.cimv.dao.entity.Notices;
import cn.edu.cimv.pojo.Message;
import cn.edu.cimv.service.NoticesService;
import cn.edu.cimv.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by 门铎 on 2016/8/2.
 */
@Controller
@RequestMapping("/cimv/notices")
public class NoticesController {
    @Autowired
    private NoticesService noticesService;
    @Autowired
    private Notices notices;
    @Autowired
    private Message message;
    @RequestMapping("list")
    public String list(Model model){
        model.addAttribute("noticesList",noticesService.queryNotices());
        return "notices/list";
    }
    @RequestMapping("new")
    public String noticesNew(){
        return "notices/new";
    }

    @RequestMapping( value = "create", method = RequestMethod.POST)
    public @ResponseBody Message create(@RequestParam("editor") String editor, @RequestParam("title") String title) {
        notices.setDate(DateUtil.toDateString(new Date()));
        notices.setContent(editor);
        notices.setTitle(title);
        noticesService.editNotices(notices);
        message.setMsg(InfoConstant.CREATE_NOTICES_SUCCESS);
        return message;
    }
    @RequestMapping(value = "delete/{id}",method = RequestMethod.GET)
    public @ResponseBody Message delete(@PathVariable("id")int id){
        noticesService.deleteNotices(id);
        message.setMsg(InfoConstant.DELETE_NOTICES_SUCCESS);
        return message;
    }
    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updatePage(@PathVariable("id")int id,Model model){
        model.addAttribute("notices",noticesService.queryNoticesById(id));
        return "notices/update";
    }
    @RequestMapping(value = "updateNotices/{id}",method = RequestMethod.POST)
    public @ResponseBody Message updateNews(@PathVariable("id")int id,
                                            @RequestParam("title")String title,
                                            @RequestParam("editor") String editor){
        //修改的内容
        notices.setId(id);
        notices.setDate(DateUtil.toDateString(new Date()));
        notices.setContent(editor);
        notices.setTitle(title);
        //更新
        noticesService.updateNotices(notices);

        message.setMsg(InfoConstant.UPDATE_NOTICES_SUCCESS);
        return message;

    }
}
